package com.slipper.system.flow.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import com.slipper.system.flow.dao.FlowInstDao;
import com.slipper.system.flow.bo.FlowInstBO;
import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;

@Service
@ReadTransactional
public class FlowInstService {
    @Resource
    private FlowInstDao flowInstDao;
    @Resource
    private FlowPendingService flowPendingService;
    @Resource
    private FlowInstNodeService flowInstNodeService;

    public FlowInstBO queryBy(String id) {
        return flowInstDao.queryBy(id);
    }

    public PageInfo<FlowInstBO> queryPage(FlowInstBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(flowInstDao.queryList(bo));
    }

    @WriteTransactional
    public Integer save(FlowInstBO bo) {
        int result;
        if (bo.getId() != null && !"".equals(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            result = flowInstDao.update(bo);
        } else {
            bo.setId(Tool.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            result = flowInstDao.insert(bo);
        }

        return result;
    }

    @WriteTransactional
    public Integer delete(FlowInstBO bo) {
        if ((bo.getId() == null || "".equals(bo.getId()))
                && (bo.getIds() == null || bo.getIds().length <= 0)) {
            throw new RuntimeException("流程参数出错！");
        }
        
        String[] ids;
        if (!(bo.getId() == null || "".equals(bo.getId()))) {
            ids = new String[] { bo.getId() };
        } else {
            ids = bo.getIds();
        }
        
        int result = 0;
        for (String id : ids) {
            result += this.delete(id);
        }
        return result;
    }

    @WriteTransactional
    public int delete(String id) {
        int result = 0;
        if (id == null || id.isEmpty()) {
            return result;
        }

        // 删除流程待办
        result += this.flowPendingService.deleteByInstId(id);

        // 删除流程实例节点
        result += this.flowInstNodeService.deleteByInstId(id);

        // 删除流程实例
        result += this.flowInstDao.delete(id);
        return result;
    }
}
